<?php
namespace app\manage\controller;
use think\Db;

class AuditCpsMng extends Base
{
    //CPS对账列表
    public function index(){
        if(request()->isAjax() || input('?export')){
            $page = input('page');
            $limit = input('limit');
            $id = input('id');
            $channelId = input('channel_id');
            $status = input('status');

            $where = [];
            !empty($id) && $where['id'] = $id;
            !empty($channelId) && $where['cps_id'] = $channelId;
            !empty($status) && $where['status'] = $status;

            if( ! $count=model('CpsBill')->where($where)->count() ){
               $this->layTable();
            }

            if(input('?export')){
                $start = 0;
                $length = 0;
            }else{
                $start = ($page-1)*$limit;
                $length = $limit;
            }

            $select = model('CpsBill')
                ->where($where)
                ->limit($start, $length)
                ->order('create_time desc')
                ->select();

            $data = [];
            $channelIdName = model('Channel')->channelIdName();
            $cpsIdType = changeValKey('ViewChannel', 'cps_id', 'cps_type');
            $cpsAuditStatus = config('cps_audit_status');
            $channelType = config('channel_type');
            foreach ($select as $k=>$v){
                if(input('?export')){
                    $data[] = [
                        'cps_type' => $channelType[ $cpsIdType[ $v['cps_id'] ] ],
                        'daytime' => date('Y/m/d', $v['start_time']) . ' - ' . date('Y/m/d', $v['end_time']),
                        'cps_id' => $v['cps_id'],
                        'cps_name' => $channelIdName[ $v['cps_id'] ],
                        'fact_money' => $v['fact_money'],
                        'pay_rate' => $v['pay_rate'] . '%',
                        'channel_rate' => $v['channel_rate'] . '%',
                        'tax_rate' => $v['tax_rate'] . '%',
                        'end_money' => $v['end_money'],
                        'contact_man' => $v['contact_man'],
                        'open_account' => formatCard($v['open_account']),
                        'open_name' => $v['open_name'],
                        'open_bank' => $v['open_bank'],
                    ];
                }else{
                    $data[] = [
                        'id' => $v['id'],
                        'cps_type' => $channelType[ $cpsIdType[ $v['cps_id'] ] ],
                        'daytime' => date('Y/m/d', $v['start_time']) . ' - ' . date('Y/m/d', $v['end_time']),
                        'cps_id' => $v['cps_id'],
                        'cps_name' => $channelIdName[ $v['cps_id'] ],
                        'pay_rate' => $v['pay_rate'] . '%',
                        'channel_rate' => $v['channel_rate'] . '%',
                        'tax_rate' => $v['tax_rate'] . '%',
                        'fact_money' => $v['fact_money'],
                        'refer_money' => $v['refer_money'],
                        'end_money' => $v['end_money'],
                        'create_time' => $v['create_time'],
                        'sure_time' => $v['sure_time'] ? date('Y-m-d H:i:s', $v['sure_time']) : '',
                        'status' => $cpsAuditStatus[ $v['status'] ],
                    ];
                }
            }

            if(input('?export')){
                array_unshift($data, ['渠道类型', '对账日期', '渠道ID', '渠道名称', '充值总额', '分成比例', '通道费', '税率', '分成总额', '收款人', '银行账号', '所属银行', '开户银行']);
                exportExcel($data, '账单', '账单');
            }

            $money1 = model('CpsBill')->where('status', 1)->sum('end_money');
            $money2 = model('CpsBill')->where('status', 2)->sum('end_money');;
            $params['money1'] = $money1 ? $money1 : 0;
            $params['money2'] = $money2 ? $money2 : 0;
            $this->layTable(0, 'CPS对账列表', $data, $count, $params);
        }else{
            $channelData = model('ViewChannel')->field('cps_id,cps_name')->where('channel_id', 1000)->order('cps_id desc')->select();
            return view('', ['channel_data'=>$channelData]);
        }
    }

    //发送账单
    public function add(){
        if(request()->isAjax()){
            $cpsId = input('cps_id');
            $payRate = input('pay_rate');
            $channelRate = input('channel_rate');
            $taxRate = input('tax_rate');
            $referMoney = input('refer_money');
            $endMoney = input('end_money');
            $factMoney = input('fact_money');
            $date = explodeTime(input('date'));
            $description = input('description');
            $contactMan = input('contact_man');
            $openAccount = input('open_account');
            $openName = input('open_name');
            $openBank = input('open_bank');

            $whereEdit['cps_id'] = $cpsId;
            if($daytime = model('CpsBill')->field('start_time, end_time, status')->where($whereEdit)->select()){
                foreach ($daytime as $k=>$v){
                    if($v['status']==4) continue;
                    if(($date['start_time']>=$v['start_time'] && $date['start_time']<=$v['end_time']) || ($date['end_time']>=$v['start_time'] && $date['end_time']<=$v['end_time'])){
                        $this->layJson(1, "{$cpsId} 渠道号存在日期重叠的账单");
                    }
                }
            }

            //cps_bill表
            $addBill['cps_id'] = $cpsId;
            $addBill['pay_rate'] = $payRate;
            $addBill['channel_rate'] = $channelRate;
            $addBill['tax_rate'] = $taxRate;
            $addBill['fact_money'] = $factMoney;
            $addBill['refer_money'] = $referMoney;
            $addBill['end_money'] = $endMoney;
            $addBill['description'] = $description;
            $addBill['create_time'] = time();
            $addBill['start_time'] = $date['start_time'];
            $addBill['end_time'] = $date['end_time'];
            $addBill['contact_man'] = $contactMan;
            $addBill['open_account'] = $openAccount;
            $addBill['open_name'] = $openName;
            $addBill['open_bank'] = $openBank;
            $addBill['status'] = 1;
            model('CpsBill')->save($addBill);
            $billId = model('CpsBill')->id;

            //cps_bill_detail表
            $allChannelId = model('Channel')->allChannelId($cpsId);
            $whereCps = "pay_time between '{$date['start_time']}' AND '{$date['end_time']}' && debug='0' && pay_result='1' && reg_cps_id in ({$allChannelId}) && channel_id=1000";
            $selectCps = Db::name('PayOrderY_'.date('Y', $date['start_time']))
                ->field('game_id, reg_cps_id, sum(total_price) as total_price')
                ->where($whereCps)
                ->group('game_id')
                ->select();

            $addDetail = [];
            foreach($selectCps as $v){
                $addDetail[] = [
                    'cps_id' => $v['reg_cps_id'],
                    'game_id' => $v['game_id'],
                    'bill_id' => $billId,
                    'money' => $v['total_price']/100
                ];
            }
            model('CpsBillDetail')->saveAll($addDetail);

            $this->layJson(0, '添加成功');
        }else{
            $channelData = model('ViewChannel')->field('cps_id,cps_name')->where('channel_id', 1000)->order('cps_id desc')->select();
            return view('', ['channel_data'=>$channelData]);
        }
    }

    //获取渠道对账时间
    public function time(){
        $where['cps_id'] = input('cps_id');
        $where['status'] = 3;
        $endTime = model('CpsBill')->where($where)->order('end_time desc')->value('end_time');
        return $endTime ? $this->layJson(0, '', date('Y-m-d', $endTime+1)) : $this->layJson(0, '', '2016-01-01');
    }

    //查询渠道数据
    public function select(){
        $cpsId = input('cps_id');
        $date = explodeTime(input('date'));

        $allChannelId = model('Channel')->allChannelId($cpsId);
        $where = "pay_time between '{$date['start_time']}' AND '{$date['end_time']}' && debug='0' && pay_result='1' && reg_cps_id in ({$allChannelId}) && channel_id=1000";
        //跨年分表
        $y1 = date('Y', $date['start_time']);
        $y2 = date('Y', $date['end_time']);
        if($y1 == $y2){
            $cpsFixedPrice = Db::name('PayOrderY_'.$y1)->where($where)->sum('total_price');
        }else{
            $field = "total_price";

            $subQuery = Db::name('PayOrderY_'.$y1)
                ->field($field)
                ->where($where)
                ->union("select {$field} from sdk_pay_order_y_{$y2} where ({$where})", true)
                ->buildSql();
            $cpsFixedPrice = Db::table($subQuery.' y')->sum('total_price');
        }

        $channel = model('Channel')->field('channel_rate, pay_rate, tax_rate, contact_man, open_account, open_name, open_bank')->where('cps_id', $cpsId)->find();

        $data['pay_rate'] = $channel['pay_rate'];
        $data['channel_rate'] = $channel['channel_rate'];
        $data['tax_rate'] = $channel['tax_rate'];
        $data['fact_money'] = round($cpsFixedPrice/100, 2);
        $data['refer_money'] = $data['end_money'] = round($data['fact_money']*($data['pay_rate']/100)*(1-($data['channel_rate']/100))*(1-($data['tax_rate']/100)), 2);
        $data['contact_man'] = $channel['contact_man'];
        $data['open_name'] = $channel['open_name'];
        $data['open_bank'] = $channel['open_bank'];
        $data['open_account'] = $channel['open_account'];
        $this->layJson(0, 'CPS对账 > 查询', $data);
    }

    //查看
    public function view(){
        if(request()->isAjax()){
            $bill = model('CpsBill')->where('id', input('id'))->find();

            if( !$count=model('CpsBillDetail')->where('bill_id', input('id'))->count() ){
                $this->layTable();
            }
            $select = model('CpsBillDetail')->where('bill_id', input('id'))->select();

            $channelIdName = model('Channel')->channelIdName();
            $gameIdName = model('Game')->gameIdName();
            foreach($select as $k=>$v){
                $data[] = array(
                    'cps_id' => $v['cps_id'],
                    'cps_name' => $channelIdName[ $v['cps_id'] ],
                    'game_id' => $v['game_id'],
                    'game_name' => $gameIdName[ $v['game_id'] ],
                    'pay_rate' => $bill['pay_rate'] . '%',
                    'channel_rate' => $bill['channel_rate'] . '%',
                    'tax_rate' => $bill['tax_rate'] . '%',
                    'money' => $v['money'],
                    'part_money' => round($v['money']*($bill['pay_rate']/100)*(1-$bill['channel_rate']/100)*(1-$bill['tax_rate']/100), 2),
                );
            }

            $this->layTable(0, 'CPS账单 > 查看', $data, $count);
        }else{
            return view();
        }
    }

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $save['contact_man'] = input('contact_man');
            $save['open_account'] = input('open_account');
            $save['open_name'] = input('open_name');
            $save['open_bank'] = input('open_bank');
            $save['description'] = input('description');
            if( model('CpsBill')->save($save, ['id'=>input('id')]) ){
                $this->layJson(0, '修改成功');
            }else{
                $this->layJson(1, '修改失败，请重试');
            }
        }else{
            $find = model('CpsBill')->field('contact_man, open_account, open_name, open_bank, description')->where('id', input('id'))->find();
            return view('', ['find'=>$find]);
        }
    }

    //删除
    public function del() {
        try{
            model('CpsBill')->where('id', input('id'))->delete();
            model('CpsBillDetail')->where('bill_id', input('id'))->delete();
        } catch (\Exception $e){
            Db::rollback();
            $this->layJson(1, $e->getMessage());
        }

        $this->layJson(0, '删除成功');
    }

    //已转账
    public function finish(){
        $where['id'] = ['in', input('id')];
        $where['status'] = 2;
        $bill = model('CpsBill')->field('id,cps_id,end_time')->where($where)->select();

        try{
            foreach ($bill as $k=>$v){
                //修改账单状态
                Db::name('CpsBill')->where('id', $v['id'])->update(['status' => 3]);

                //修改渠道最后对账时间
                Db::name('Channel')->where('cps_id', $v['cps_id'])->update(['audit_time'=>time()]);
            }
        } catch (\Exception $e){
            Db::rollback();
            $this->layJson(1, $e->getMessage());
        }

        $this->layJson(0, '修改成功');
    }

    //设置过期时间
    public function setExpire(){
        if(request()->isAjax()){
            $save['value'] = input('date') ? strtotime(input('date')) : '';
            if( model('CommonOption')->save($save, ['id'=>200]) ){
                $this->layJson(0, '修改成功');
            }else{
                $this->layJson(1, '修改失败，请重试');
            }
        }else{
            $time = model('CommonOption')->where('id', 200)->value('value');
            $date = $time ? date('Y-m-d H:i:s', $time) : '';
            return view('', ['date'=>$date]);
        }
    }

    //手动过期
    public function handExpire(){
        if(model('CpsBill')->save(['status'=>4], ['status'=>1]) !== false){
            $this->layJson(0, '修改成功');
        }else{
            $this->layJson(1, '修改失败，请联系管理员');
        }
    }
}